//
//  XYXEmoticonCell.swift
//  表情键盘
//
//  Created by 亚杏 on 2017/6/13.
//  Copyright © 2017年 oms. All rights reserved.
//

import UIKit

@objc protocol XYXEmoticonCellDelegate: NSObjectProtocol {

    ///cell 选中表情后，将模型传到控制器
    func emoticonCellDidSelectedEmoticon(cell: XYXEmoticonCell?, em: XYXEmoticonModel?)
}


// 表情的页面cell，
// 每个cell就是和collectionView一样大小
// 每个cell中用九宫格算法，自行添加20个表情
// 最后一个位置放删除按钮
class XYXEmoticonCell: UICollectionViewCell {

    /// 代理
    weak var delegate: XYXEmoticonCellDelegate?

    @IBOutlet weak var label: UILabel!

    //当前页面的表情模型，最多20个
    var emoticons: [XYXEmoticonModel]? {
        didSet {
            print("表情包的数量\(String(describing: emoticons?.count))")
            //1.隐藏所有的按钮
            for v in contentView.subviews {
                v.isHidden = true
            }

            //显示删除按钮
            contentView.subviews.last?.isHidden = false

            //2. 遍历表情模型数组
            for (i,em) in (emoticons ?? []).enumerated() {
                //1.取出按钮
                if let btn = contentView.subviews[i] as? UIButton {
                    //设置图像，如果图像为nil，会清空图像，避免复用
                    btn.setImage(em.image, for: .normal)

                    //设置emoji字符串
                    btn.setTitle(em.emoji, for: .normal)
                    btn.isHidden = false

                }
            }
        }
    }

    //表情选择提示视图
    private lazy var tipView = XYXEmoticonTipView()


    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func willMove(toWindow newWindow: UIWindow?) {
        super.willMove(toWindow: newWindow)

        guard let w = newWindow else {
            return
        }

        //将提示视图添加到窗口上
        w.addSubview(tipView)
        tipView.isHidden = true
    }

    //长按手势识别 - 非常重要
    // 可以保证一个对象监听两种点击手势，不需要考虑手势冲突
    @objc private func longGesture(gesture: UILongPressGestureRecognizer) {

        //1.获取触摸位置
        let location = gesture.location(in: self)

        //2.获取触摸位置对应的按钮
        guard let button = buttonWithLocation(location: location) else{
            tipView.isHidden = true
            return
        }

        //3.处理手势
        switch gesture.state {
        case .began, .changed:

            tipView.isHidden = false

            //坐标系的转换 - 将按钮参照的cell的坐标系转换到window的坐标位置
            let center = self.convert(button.center, to: window)

            //设置提示视图的位置
            tipView.center = center

            //设置提示视图的表情模型
            if button.tag < (emoticons?.count)! {
                tipView.emoticon = emoticons?[button.tag]
            }

        case .ended:
            tipView.isHidden = true
            selectedEmoticonBtn(button: button)

        case .cancelled, .failed:
            tipView.isHidden = true

        default:
            break
        }
        print(button)

    }

    private func buttonWithLocation(location: CGPoint) -> UIButton? {
        //遍历所有子视图，如果可见，同时在 location 确认是按钮
        for btn in contentView.subviews {
            if btn.frame.contains(location) && !btn.isHidden && btn != contentView.subviews.last {
                return btn as? UIButton
            }
        }

        return nil
    }


    //MARK:按钮监听方法
    @objc private func selectedEmoticonBtn(button: UIButton) {
        //1.取tag , 0~20
        let tag = button.tag

        //2.根据tag判断是否是删除按钮，如果不是删除按钮，取表情
        var em: XYXEmoticonModel!
        if tag < (emoticons?.count)! {
            em = emoticons?[tag]
        }

        delegate?.emoticonCellDidSelectedEmoticon(cell: self, em: em)
    }


    //从XIB加载，是xib中定义的大小，不是size的大小
    //从纯代码创建，bounds是对的
    private func setupUI() {
        let rowCount = 3
        let colCount = 7

        //左右间距
        let leftMargin: CGFloat = 8
        //底部间距，为分页控件位置
        let bottomMargin: CGFloat = 16
        let w = (bounds.width - 2 * leftMargin) / CGFloat(colCount)
        let h = (bounds.height - bottomMargin) / CGFloat(rowCount)

        //连续创建21个按钮
        for i in 0..<21 {
            let row = i / colCount
            let column = i % colCount

            let btn = UIButton()

            let x = leftMargin + CGFloat(column) * w
            let y = CGFloat(row) * h
            btn.frame = CGRect(x: x, y: y, width: w, height: h)

            //设置btn的字体大小
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 32)
            contentView.addSubview(btn)

            //设置按钮的tag
            btn.tag = i

            btn.addTarget(self, action: #selector(selectedEmoticonBtn), for: .touchUpInside)

        }

        // 取出末尾的删除按钮
        let removebtn = contentView.subviews.last as! UIButton
        let image = UIImage(named: "compose_emotion_delete_highlighted", in: XYXEmoticonManager.shared.bundle, compatibleWith: nil)
        removebtn.setImage(image, for: .normal)

        //添加长按手势
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longGesture))
        longPress.minimumPressDuration = 0.1
        addGestureRecognizer(longPress)
    }
    
}
